<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author PR
-->
<template>
  <div>
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> {{ getTitle.value }} </span>
      </template>
      <template #toolbar>
        <a-button type="primary" @click="handleForm({})" v-auth="'_3d:pd:wms3dPdH:edit'">
          <Icon icon="fluent:add-12-filled" /> {{ t('新增') }}
        </a-button>
        <!-- v-auth="'_3d:pd:wms3dPdH:down'" -->
        <!-- <a-button type="primary" @click="handleDown({ })">
          <Icon icon="fluent:add-12-filled" /> {{ t('下架') }}
        </a-button> -->
        <a-button type="primary" @click="handleUpdateSpQty({})">
          <Icon icon="fluent:add-12-filled" /> {{ t('更新实盘数量') }}
        </a-button>
      </template>
      <template #firstColumn="{ record }">
        <a @click="handleForm({ id: record.id })">
          {{ record.cwhcode }}
        </a>
      </template>
    </BasicTable>
    <InputForm @register="registerDrawer" @success="handleSuccess" />
    <BpmRuntimeTrace @register="registerTraceModal" />
    <component
      :is="inputFormComponent"
      v-model:visible="inputFormVisible"
      @register="registerDrawerBpmMyTask"
      @success="handleSuccess"
    />
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'Views3dPdWms3dPdHList',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, shallowRef } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
  import {
    wms3dPdHDelete,
    wms3dPdHListData,
    wms3dPdHDown,
    wms3dPdHUpdateSpQty,
    wms3dPdHForm,
    Wms3dPdH,
  } from '/@/api/wms/_3d/wms3dPdH';
  import { useDrawer } from '/@/components/Drawer';
  import { FormProps } from '/@/components/Form';
  import InputForm from './form.vue';
  import { dynamicImport } from '/@/router/helper/routeHelper';
  import { bpmTaskDefForm } from '/@/api/bpm/myTask';
  import { createAsyncComponent } from '/@/utils/factory/createAsyncComponent';
  import qs from 'qs';
  import { useModal } from '/@/components/Modal';
  import { BpmRuntimeTrace } from '/@/components/Bpm';

  const { t } = useI18n('_3d.pd.wms3dPdH');
  const { showMessage } = useMessage();
  const data = ref<Wms3dPdH>({} as Wms3dPdH);
  const getTitle = {
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: router.currentRoute.value.meta.title || t('盘点单管理'),
  };

  const searchForm: FormProps = {
    baseColProps: { lg: 6, md: 8 },
    labelWidth: 90,
    schemas: [
      {
        label: t('仓库编码'),
        field: 'cwhcode',
        component: 'Input',
      },
      {
        label: t('仓库名称'),
        field: 'cwhname',
        component: 'Input',
      },
      {
        label: t('存货编码'),
        field: 'cinvcode',
        component: 'Input',
      },
      {
        label: t('存货名称'),
        field: 'cinvname',
        component: 'Input',
      },
      {
        label: t('批次'),
        field: 'cbatch',
        component: 'Input',
      },

      {
        label: t('盘点状态'),
        field: 'pdStatus',
        component: 'Select',
        componentProps: {
          dictType: 'wms_pd_status',
          allowClear: true,
          onChange: handleSuccess,
        },
      },
      {
        label: t('状态'),
        field: 'status',
        component: 'Select',
        componentProps: {
          dictType: 'sys_bpm_status',
          allowClear: true,
          onChange: handleSuccess,
        },
      },
    ],
  };

  const tableColumns: BasicColumn[] = [
    {
      title: t('仓库编码'),
      dataIndex: 'cwhcode',
      key: 'a.cwhcode',
      sorter: true,
      width: 100,
      align: 'left',
      slot: 'firstColumn',
      fixed: 'left',
    },
    {
      title: t('仓库名称'),
      dataIndex: 'cwhname',
      key: 'a.cwhname',
      sorter: true,
      width: 130,
      align: 'left',
      fixed: 'left',
    },
    {
      title: t('存货编码'),
      dataIndex: 'cinvcode',
      key: 'a.cinvcode',
      sorter: true,
      width: 130,
      align: 'left',
      fixed: 'left',
    },
    {
      title: t('存货名称'),
      dataIndex: 'cinvname',
      key: 'a.cinvname',
      sorter: true,
      width: 230,
      align: 'left',
      fixed: 'left',
    },
    {
      title: t('规格型号'),
      dataIndex: 'cinvstd',
      key: 'a.cinvstd',
      sorter: true,
      width: 200,
      align: 'left',
    },
    {
      title: t('批次'),
      dataIndex: 'cbatch',
      key: 'a.cbatch',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('现存量'),
      dataIndex: 'iqty',
      key: 'a.iqty',
      sorter: true,
      width: 130,
      align: 'right',
    },
    {
      title: t('实盘数量'),
      dataIndex: 'pdQty',
      key: 'a.pd_qty',
      sorter: true,
      width: 130,
      align: 'right',
    },
    {
      title: t('下架数量'),
      dataIndex: 'downQty',
      key: 'a.down_qty',
      sorter: true,
      width: 130,
      align: 'right',
    },
    {
      title: t('上架数量'),
      dataIndex: 'upQty',
      key: 'a.up_qty',
      sorter: true,
      width: 130,
      align: 'right',
    },
    {
      title: t('盘点状态'),
      dataIndex: 'pdStatus',
      key: 'a.pd_status',
      sorter: true,
      dictType: 'wms_pd_status',
      width: 100,
      align: 'center',
      fixed: 'right',
    },
    {
      title: t('状态'),
      dataIndex: 'status',
      key: 'a.status',
      sorter: true,
      width: 130,
      align: 'center',
      dictType: 'sys_bpm_status',
      fixed: 'right',
    },
    {
      title: t('修改时间'),
      dataIndex: 'updateDate',
      key: 'a.update_date',
      sorter: true,
      width: 130,
      align: 'center',
    },
    {
      title: t('备注'),
      dataIndex: 'remarks',
      key: 'a.remarks',
      sorter: true,
      width: 130,
      align: 'left',
    },
  ];

  const actionColumn: BasicColumn = {
    width: 160,
    actions: (record: Recordable) => [
      {
        icon: 'fluent:flowchart-20-regular',
        title: t('流程追踪'),
        onClick: handleTrace.bind(this, record),
        ifShow: () => record.status != '9',
      },
      {
        icon: 'mdi:checkbox-marked-outline',
        title: t('任务办理'),
        onClick: handleBpmMyTask.bind(this, { id: record.id }),
        ifShow: () => record.status == '4' || record.status == '5' || record.status == '6',
      },
      {
        icon: 'clarity:note-edit-line',
        title: t('编辑盘点单'),
        onClick: handleForm.bind(this, { id: record.id }),
        auth: '_3d:pd:wms3dPdH:edit',
        ifShow: () => record.status == '9',
      },
      {
        icon: 'ant-design:delete-outlined',
        color: 'error',
        title: t('删除盘点单'),
        popConfirm: {
          title: t('是否确认删除盘点单'),
          confirm: handleDelete.bind(this, { id: record.id }),
        },
        ifShow: () => record.status == '9',
        auth: '_3d:pd:wms3dPdH:edit',
      },
    ],
  };

  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerTable, { reload, getForm, getSelectRows }] = useTable({
    api: wms3dPdHListData,
    beforeFetch: (params) => {
      return params;
    },
    columns: tableColumns,
    actionColumn: actionColumn,
    formConfig: searchForm,
    showTableSetting: true,
    useSearchForm: true,
    canResize: true,
    rowSelection: {
      type: 'radio',
    },
  });

  function handleForm(record: Recordable) {
    openDrawer(true, record);
  }

  async function handleDelete(record: Recordable) {
    const res = await wms3dPdHDelete(record);
    showMessage(res.message);
    handleSuccess();
  }

  function handleSuccess() {
    reload();
  }

  async function handleDown() {
    if(!!getSelectRows()[0]['downQty']){
      showMessage('不能重复下架！！');
      return;
    }
    if(getSelectRows()[0]['status'] == 0){
      showMessage('盘点单已完成，无法下架！！');
      return;
    }
    if (getSelectRows().length) {
      console.log(getSelectRows());
      const id = getSelectRows()[0]['id'];
      const res = await wms3dPdHDown({ id: id });
      showMessage(res.message);
      handleSuccess();
    } else {
      showMessage('请选择一行数据！！');
    }
  }

  async function handleUpdateSpQty() {
    if(getSelectRows()[0]['status'] == 0){
      showMessage('盘点单已完成，无法更改！！');
      return;
    }
    if (getSelectRows().length) {
      // const id = getSelectRows()[0]['id'];
      // const data = await bpmGetTask({ 'procIns.formKey': 'flow_pd', 'procIns.bizKey': id });
      // console.log(data, 'data');
      // const taskId = data.id;
      // const procInsId = data?.procIns?.id;
      // const activityId = data.activityId;
      // const bpm = {
      //   taskId: taskId,
      //   procInsId: procInsId,
      //   activityId: activityId,
      //   bizKey: id,
      //   bizType: 'flow_pd',
      // };
      // const params = { id: id, status: 4 };
      // const dataForm = await wms3dPdHForm({ id: id });
      // console.log(dataForm, 'dataForm');
      // data.value = (dataForm.wms3dPdH || {}) as Wms3dPdH;
      // data.value.bpm = bpm;
      // data.value.status = 4;
      // const res = await wms3dPdHUpdateSpQty(params, data.value);
      // if (res.result == 'true') {
      //   showMessage(res.message);
      //   handleSuccess();
      // } else {
      //   showMessage(res.message);
      // }
      handleForm({ id: getSelectRows()[0]['id'], status: 4 });
    } else {
      showMessage('请选择一行数据！！');
    }
  }

  const [registerTraceModal, { openModal: traceModel }] = useModal();
  function handleTrace(record: Recordable) {
    traceModel(true, { formKey: 'flow_pd', bizKey: record.id });
  }


  const [registerDrawerBpmMyTask, { setDrawerData }] = useDrawer();
  const inputFormComponent = shallowRef<Nullable<any>>(null);
  const inputFormVisible = ref<Boolean>(false);

  async function handleBpmMyTask(record: Recordable) {
    const data = await bpmTaskDefForm({ formKey: 'flow_pd', bizKey: record.id });
    if (data.result == 'true') {
      const url = data.pcUrl;
      const idx = url.indexOf('?');
      // component
      let component: ReturnType<typeof defineComponent>;
      const compStr = idx == -1 ? url : url.substring(0, idx);
      if (compStr && compStr != '') {
        const imp = dynamicImport(compStr);
        if (imp) component = createAsyncComponent(imp);
      }
      // params
      let params = {};
      const paramStr = idx == -1 ? '' : url.substring(idx + 1);
      if (paramStr && paramStr != '') {
        params = qs.parse(paramStr);
      }
      // open
      if (component) {
        inputFormComponent.value = component;
        inputFormVisible.value = true;
        setDrawerData(params);
      }
    } else {
      showMessage(data.message);
    }
  }

</script>
